const koa = require("koa");
const router = require("koa-router")();
const Top250Model = require("./models/top250");
const UserModel = require("./models/user");
const cors = require("koa2-cors");
const bodyParser = require("koa-bodyparser");
const app = new koa();
/* top250路由去读取数据库中的数据 */
router.get("/top250",async ctx=>{
    console.log(ctx.query);
    var {start,count} = ctx.query;
    console.log(start)
    if(start == undefined){
        start = 0
    }
    if(count == undefined){
        count = 5
    }
    /* http://localhost:8080/top250?start=0&count=5 */
    var data = await Top250Model.find({}).skip(Number(start)).limit(Number(count))
    // ctx.body = "top250"
    ctx.body = {
        data,
        code:200
    }
})
router.post("/doAdd",async ctx=>{
    console.log(ctx.request.body)
    var {name,rating} = ctx.request.body;
    
    var db = new Top250Model({name,rating});
    db.save(err=>{
        if(err) throw err;
    })
    ctx.redirect("/top250")
})
router.post("/doCollect",async ctx=>{
    // console.log(ctx.request.body)
    var {id,like} = ctx.request.body;
    var data = await Top250Model.find({_id:id})
    var obj = data[0];
    if(like == "true"){
        //push
        console.log(obj)
        await UserModel.updateOne({name:"chengchao"},{$push:{collects:obj}})
    }else{
        //pull
        console.log(obj)
        await UserModel.updateOne({name:"chengchao"},{$pull:{collects:{_id:id}}})
    }
})
/* 删除数据库中对应的数据 */
router.post("/doDelete",async ctx=>{
    // console.log(ctx.request.body);
    var {id} = ctx.request.body;
    await Top250Model.remove({_id:id});
    ctx.redirect("/top250")
})
/* 点赞 */
router.post("/doLike",async ctx=>{
    // console.log(ctx.request.body)
    var {id,like} = ctx.request.body;
    await Top250Model.updateOne({_id:id},{$set:{like}})
})
app.use(cors());
app.use(bodyParser());
app.use(router.routes());
app.listen(8080)